import { Button, message, Popconfirm, Input, Select } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import _ from 'lodash';
import request from '@/utils/request';
import apiPath from '@/utils/apiPath.js';

const PageContent = () => {
  const [inputVal, setInputVal] = useState("");
  const [voiceType, setVoiceType] = useState(0);
  const audioRef = useRef();

  const reqTextToVoiceApi = async() => {
    console.log(inputVal);
    const postForm = {
      text: inputVal,
      voice_type: voiceType
    };
    const hide = message.loading('正在调用');
    try {
      let res = await request(apiPath.DEMO_VOICE, {
        method: 'POST',
        data: postForm,
      });
      hide();
      message.success(`调用成功`);
      return res.data;
    } catch (error) {
      console.error(error);
      hide();
      return false;
    }
  }

  const invokeAudioPlay = (data) => {
    audioRef.current.src = `data:audio/wav;base64,${data}`;        
  }

  return (
    <PageContainer>
      <audio 
        ref={audioRef}
        autobuffer="autobuffer" 
        autoPlay>
        <source src="" />
      </audio>
      <Input 
        style={{
          width: '300px',
          marginBottom: '20px'
        }}
        placeholder=""
        onChange={(e) => {
          setInputVal(e.target.value);
        }}
      /> 
      <br/>
      <Select 
        style={{
          width: '300px',
          marginBottom: '20px'
        }}
        options={[
          {
            label: '云小宁，亲和女声', 
            value: 0
          },
          {
            label: '云小奇，亲和男声', 
            value: 1
          },
          {
            label: '云小晚，成熟男声', 
            value: 2
          },
          {
            label: '云小叶，温暖女声', 
            value: 4
          },
          {
            label: '云小欣，情感女声', 
            value: 5
          },
          {
            label: '云小龙，情感男声', 
            value: 6
          },
          {
            label: '云小曼，客服女声', 
            value: 7
          },
          {
            label: '智瑜，情感女声', 
            value: 101001
          },
          {
            label: '智聆，通用女声', 
            value: 101002
          },
          {
            label: '智美，客服女声', 
            value: 101003
          },
        ]}
        placeholder="请选择"
        allowClear
        onChange={(value) => {
          setVoiceType(value);
        }}
      />
      <br/>
      <Button
        type="primary"
        key="primary"
        onClick={async () => {
          let data = await reqTextToVoiceApi();
          invokeAudioPlay(data);
        }}
      >
        播放
      </Button>
    </PageContainer>
  );
};

export default PageContent;
